package com.eoner.managerlibrary.version;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.eoner.commonbean.config.SystemVersionBean;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.common.config.Config;
import com.eoner.baselib.application.BaseApplication;
import com.eoner.managerlibrary.R;
import com.eoner.managerlibrary.system.callback.SystemConfigCallBack;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import io.reactivex.disposables.Disposable;

import static android.content.Context.DOWNLOAD_SERVICE;

public class VersionManager {

    public static VersionManager instance;
    public static VersionManager getInstance() {
        synchronized (VersionManager.class) {
            if (instance == null) {
                instance = new VersionManager();
            }
        }
        return instance;
    }


    private WeakReference<Activity>activity;
    private String apkurl;
    private ProgressDialog pDialog;//数据加载显示
    RxPermissions rxPermissions;
    private boolean isDdismiss = true;
    Disposable disposable;
    RxBus rxBus;
    private UpdateDialog updateDialog;

    private Context context = BaseApplication.getInstance();

    public String getApkurl() {
        return apkurl;
    }

    public Activity getActivity() {
        if (activity != null) {
            return activity.get();
        }
        return null;
    }

    public VersionManager() {
        rxBus = RxBus.$();
    }

    public VersionManager setActivity(Activity activity) {
        this.activity = new WeakReference<Activity>(activity);
        this.rxPermissions = null;
        this.rxPermissions = new RxPermissions(activity);
        return this;
    }

    /**
     * 检测更新 ,noFrontBack:不是切换前后台
     * */
    public VersionManager checkVersionUpdate(boolean noFrontBack ) {


        if (Config.update_app_show) {
            return this;
        }
        if (SystemConfigStorage.getInstance().isFirstRequest()) {
            SystemConfigStorage.getInstance().setFirstRequest(false);
            //1.第一次进入直接拿缓存信息
            if (SystemConfigStorage.getInstance().getVersion() != null) {
                //版本更新
                updateVersion(SystemConfigStorage.getInstance().getVersion(),noFrontBack);
            } else {
                //2.如果缓存信息没有,请求接口
                requestCheckVersionUpdate(noFrontBack);
            }
        } else {
            //3.之后每次都请求接口
            requestCheckVersionUpdate(noFrontBack);
        }
        return this;
    }

    /**
    * 请求接口检测更新 ,noFrontBack:不是切换前后台
    * */
    public void requestCheckVersionUpdate(boolean noFrontBack) {
        Map<String,String> map = new HashMap<>();
        map.put("client_type","android");
        SystemConfigStorage.getInstance().getSystemConfig(new SystemConfigCallBack() {
            @Override
            public void onSuccess() {
                //版本更新
                updateVersion(SystemConfigStorage.getInstance().getVersion(),noFrontBack);
            }

            @Override
            public void onFailed(String errMsg) {

            }
        });
    }

    private void updateVersion(SystemVersionBean versionBean, boolean noFrontBack) {
        if (getActivity() == null) {
            return;
        }
        if (!TextUtils.isEmpty(versionBean.getResource_url())) {
            if (Config.update_app_show && updateDialog != null) {
                if ("0".equals(versionBean.getUpdate_status())
                        ||("".equals(versionBean.getVersion_number())
                        && !SPUtils.getInstance().getString(Config.IS_APP_UPDATE,"").equals(versionBean.getUpdate_status()))) {
                    updateDialog.dismiss();
                    Config.update_app_show = false;
                    SPUtils.getInstance().put(Config.UPDATE_APP_TIME,"");
                }
            }
        }
        SPUtils.getInstance().put(Config.IS_APP_UPDATE,(versionBean == null ||
                TextUtils.isEmpty(versionBean.getUpdate_status()))?"0":versionBean.getUpdate_status());
        if ("0".equals(versionBean.getUpdate_status()) && !noFrontBack) {
            rxBus.post(Config.UPDATE_DIALOG_DISMISS, getActivity().getClass().getSimpleName());
        }
        String time = SPUtils.getInstance().getString(Config.UPDATE_APP_TIME,"");
        //判断如果updateStatus 为2 且 不在同一天
        if(!Config.update_app_show && versionBean.getUpdate_status().equals("1") && !TimeUtil.isSameDay(System.currentTimeMillis()+"",time)) {
            setStart(versionBean,versionBean.getResource_url());
            return;
        }
        if (versionBean.getUpdate_status().equals("2") && !Config.update_app_show) {
            setStart(versionBean,versionBean.getResource_url());
        }
    }

    private void setStart(final SystemVersionBean bean, String apkurl) {
        this.apkurl = apkurl;
        if (getActivity() == null) return;
        updateDialog = new UpdateDialog(getActivity());
        isUpdate = bean.getUpdate_status();
        if("2".equals(bean.getUpdate_status())){//强制更新
            updateDialog.hiddenCancel(true);
            updateDialog.setOptionClickListerner(new UpdateDialog.OptionClickListerner() {
                @Override
                public void cancle() {
                }

                @Override
                public void update() {
                    clickDownLoad(bean.getAndroid_download_type());
                }
            });
            if (!getActivity().isFinishing()){
                updateDialog.show();
                Config.update_app_show = true;
                SPUtils.getInstance().put(Config.UPDATE_APP_TIME,"");
                updateDialog.setUpdateInfo(bean);
            }
        } else if("1".equals(bean.getUpdate_status())){
            updateDialog.hiddenCancel(false);
            updateDialog.setOptionClickListerner(new UpdateDialog.OptionClickListerner() {
                @Override
                public void cancle() {
                }

                @Override
                public void update() {
                    clickDownLoad(bean.getAndroid_download_type());
                }
            });
            if (!getActivity().isFinishing()){
                updateDialog.show();
                Config.update_app_show = true;
                SPUtils.getInstance().put(Config.UPDATE_APP_TIME,  System.currentTimeMillis()+"");
                updateDialog.setUpdateInfo(bean);
            }
        }
    }

    /**
     * 判断是应用内容直接下载，还是跳转浏览器下载
     * @param downloadType 1 app内 2 H5下载更新
    * */
    private void clickDownLoad(String downloadType) {
        if (downloadType != null) {
            if (downloadType.equals("2")) {
                downLoadByApp();
            } else {
                downloadByWeb();
            }
        } else {
            downLoadByApp();
        }
    }

    private void downLoadByApp() {
        updateDialog.dismiss();
        //应对6.0以上版本申请权限
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
            if (getActivity() == null) {
                Toast.makeText(getActivity(),"权限申请失败啦",Toast.LENGTH_SHORT).show();
                Config.update_app_show = false;
                return;
            }
            boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (!hasPermissions){
                new PermissionDialog(getActivity(), "开启存储权限", "下载安装包需要使用存储权限，请在下一个页面点击“允许”",
                        R.mipmap.icon_permission_storage, new PermissionDialog.PermissionClickListener() {
                    @Override
                    public void onConfirm() {
                        requestPermissions();
                    }

                    @Override
                    public void onCancel() {
                        Config.update_app_show = false;
                        Toast.makeText(getActivity(),"权限申请失败啦",Toast.LENGTH_SHORT).show();
                    }
                }).show();
            }else {
                downloadFile();
            }
        }else {
            downloadFile();
        }
    }

    //直接跳转浏览器
    private void downloadByWeb() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri content_uri_browsers = Uri.parse(apkurl);
        intent.setData(content_uri_browsers);
        getActivity().startActivity(intent);
    }

    private void requestPermissions(){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        downloadFile();
                    } else if (permission.shouldShowRequestPermissionRationale){
                        Config.update_app_show = false;
                        // Denied permission without ask never again
                        Toast.makeText(getActivity(),"权限申请失败啦",Toast.LENGTH_SHORT).show();
                    } else {
                        Config.update_app_show = false;
                        // Denied permission with ask never again
                        // Need to go to the settings
                        Toast.makeText(getActivity(),"权限申请失败",Toast.LENGTH_SHORT).show();
                    }
                });
    }

    File file;
    private long currentDownloadID;
    private boolean idDownloading = true, idDownloadSuccess = false;
    private AsyncTask<Integer, Integer, Boolean> asyncTask;
    private String isUpdate;

    private CompleteReceiver completeReceiver;
    //下载完成广播
    private class CompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            long myDownLoadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);  //拿到下载的Id
            if (myDownLoadId == currentDownloadID){

                idDownloading = false;
                if (!asyncTask.isCancelled()) {
                    asyncTask.cancel(true);
                }
                Config.update_app_show = false;

                if (completeReceiver != null)
                    VersionManager.this.context.unregisterReceiver(completeReceiver);

                installApk(file);
            }
        }
    }

    /**
     * @throws
     */
    @SuppressLint("StaticFieldLeak")
    private void downloadFile() {
        if (!"2".equals(isUpdate) && completeReceiver == null){//注册广播
            completeReceiver = new CompleteReceiver();
            context.registerReceiver(completeReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }

        ShowDialog(null);
        String filesd = Environment.getExternalStorageDirectory().getPath();
        File tmpFile = new File(filesd + "/flowerc");
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        file = new File(filesd + "/flowerc/flowerc"+System.currentTimeMillis()+".apk");

        asyncTask = new AsyncTask<Integer, Integer, Boolean>() {

            @Override
            protected Boolean doInBackground(Integer... strings) {
                DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(getApkurl()));
                downloadRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                // 下载标题
                downloadRequest.setTitle("中华大师汇版本更新");
                downloadRequest.setDestinationUri(Uri.fromFile(file));

                DownloadManager manager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
                if (manager != null) {
                    currentDownloadID = manager.enqueue(downloadRequest);
                    Log.e("====", "DownloadManager start downloading ---------");
                    // 获取下载进度
                    while (idDownloading) {
                        if (!isNetWorkAvailable(context)) {
                            handler.sendEmptyMessage(-1);
                            idDownloadSuccess = false;
                            break;
                        }
                        DownloadManager.Query query = new DownloadManager.Query();
                        query.setFilterById(currentDownloadID);
                        Cursor cursor = manager.query(query);

                        if (cursor != null && cursor.moveToFirst()) {
                            long bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                            long bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                            final int downloadProgress = (int) (bytesDownloaded * 100 / bytesTotal);
                            publishProgress(downloadProgress);
                            if (downloadProgress == 100) {
                                currentDownloadID = -1;
                                idDownloadSuccess = true;
                                cursor.close();
                                break;
                            } else {
                                try {
                                    if (isNetWorkAvailable(context)) {
                                        Thread.sleep(100);
                                    } else {
                                        handler.sendEmptyMessage(-1);
                                        idDownloadSuccess = false;
                                        cursor.close();
                                        break;
                                    }
                                } catch (Exception e) {
                                    cursor.close();
                                    StringWriter stringWriter = new StringWriter();
                                    e.printStackTrace(new PrintWriter(stringWriter, true));
                                    handler.sendEmptyMessage(-1);
                                }
                            }
                        }
                        if (cursor != null && !cursor.isClosed()){
                            cursor.close();
                        }
                    }
                }
                return true;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                idDownloading = false;
                if (aBoolean && idDownloadSuccess) {
//                    handler.sendEmptyMessage(2);
                } else {
                    handler.sendEmptyMessage(-1);
                }
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                int value = values[0];
                if (value < 100) {
                    if (pDialog != null && pDialog.isShowing()) {
                        pDialog.setProgress(value);
                    }
//                    Message message = handler.obtainMessage();
//                    message.what = 1;
//                    message.arg1 = value;
//                    handler.sendMessage(message);
                }else {
                    if (pDialog != null && pDialog.isShowing()) {
                        pDialog.dismiss();
                    }
                    Config.update_app_show = false;
                    if (file != null && file.exists()) {
                        installApk(file);
                    }
                }
            }
        };
        asyncTask.execute(20);
    }

    public static boolean isNetWorkAvailable(Context context){
        boolean isAvailable = false ;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if(networkInfo!=null && networkInfo.isAvailable()){
            isAvailable = true;
        }
        return isAvailable;
    }

    public Handler handler = new Handler(Looper.getMainLooper()){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case -1:
                    ToastUtil.showToast("下载失败，请重新下载");
                    if ("2".equals(isUpdate)){
                        postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                UtilActivity.finishAll();
                                System.exit(0);
                            }
                        },277);
                    } else {
                        if (pDialog != null && pDialog.isShowing()) {
                            pDialog.dismiss();
                            Config.update_app_show = false;
                        }
                    }
                    break;
            }
        }
    };

    /**
     * 数据加载框
     *
     * @param message
     * @return
     */
    public Dialog ShowDialog(String message) {
        if (getActivity() == null) {
            return null;
        }
        if (getActivity()!=null && getActivity().isFinishing()) {
            return null;
        }
        if (message == null) {
            message = "正在下载，请稍等...";
        }

        getDialogDismiss();

        if("2".equals(isUpdate)) {
            pDialog = new ProgressDialog(getActivity());
            pDialog.setTitle(getActivity().getString(R.string.app_name));
            pDialog.setMessage(message);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (asyncTask != null) {
                        DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
                        if (currentDownloadID >= 0) {
                            if (downloadManager != null) {
                                downloadManager.remove(currentDownloadID);
                            }
                        }
                        idDownloading = false;
                        asyncTask.cancel(true);
                        Config.update_app_show = false;
                    }
                }
            });
            pDialog.setMax(100);
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.show();
        }
        return pDialog;
    }


    /**
     * 关闭提示框
     *
     * @return
     */
    public Dialog getDialogDismiss() {
        if (pDialog != null && pDialog.isShowing() && isDdismiss) {
            pDialog.dismiss();
            //cancel();
            pDialog = null;

        }
        return pDialog;
    }

    // 安装Apk：
    private void install(String fileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(fileName)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 安装 apk 文件
     * 安卓官方为了提高私有文件的安全性，面向 Android 7.0 或更高版本的应用私有目录被限制访问
     * 分享私有文件内容的推荐方法是使用 FileProvider
     * @param apkFile
     */
    public void installApk(File apkFile) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, "com.masterclient.app.fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }

        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            context.startActivity(intent);
        }
//        context.startActivity(intent);
    }

    /**
     * 取消当前网络请求
     */
    public void cancel() {
        if (disposable != null) {
            //client.cancelAllRequests(true);
            disposable.dispose();
        }
    }


    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

}
